import axios from "axios";
import footer from "../footer/footer";
import ToolBar from "../tool_bar/ToolBar";
import debounce from "@u/debounce";
import render from "@u/render";

import "./HomeMainPage.scss"

const renderHomePageInfo = (data) => {
    // todo 头大不想抽了
    return data.map(item => {
        const { body: { floor_name, more_text, left_ad: { items }, product_list, tab_content } } = item
        return `<div class="home-page-info">
                    <div class="page-hd">
                          <h2 class="title">${floor_name}</h3>
                           <div class="more"> ${!more_text
                ? `<div class="tab-list">${tab_content.map((i, n) => `<a tid="${i.tab_id}" ${n === 0 ? 'class="active"' : ''}href="javascript:void(0)">${i.tab_name}</a>`).join("")}</div>`
                : `<a href="javascript:void(0)">${more_text}<i class="iconfont icon-more"></i></a>`}      
                                </div>
                            </div>
                            <div class="page-content">
                                <div class="left-ad">
                                    ${items.map(i => `<img ${items.length === 2 ? "class='img3'" : ''}" src="${i.img_url}">`).join("")}
                                </div>
                                ${!tab_content
                ? `<div class="product-list">` + product_list.map(i => `<li><a href="javascript:void(0)"><img src="${i.img_url}"><span class="title">${i.product_name}</span><span class="desc">${i.product_brief}</span>${i.product_org_price !== i.product_price ? `<div class="price"><span>${i.product_price}元</span><del><span>${i.product_org_price}元</span></del></div>` : `<span class="price">${i.product_price}元起</span>`}</a></li>`).join('') + '</div>'
                : `<div class="product-list-tab" >` + tab_content.map((t, n) => {
                    let { product_list, more_text, tab_name, tab_id } = t
                    let temp = `<div class="tab-list-item ${n === 0 ? 'active' : ''}" tname="${tab_name}" tid="${tab_id}" >`
                    const len = product_list.length;
                    temp += product_list.map((i, n) => n < 7
                        ? `<li class="${len < 7 && n > 3 ? 'row' : ''}"><a href="javascript:void(0)"><img src="${i.img_url}"><span class="title">${i.product_name}</span><span class="desc">${i.product_brief}</span>${i.product_price !== i.product_org_price ? `<div class="price"><span>${i.product_price}元</span><del><span>${i.product_org_price}元</span></del></div>` : `<span class="price">${i.product_price}元</span>`}</a></li>${len < 7 && n === len - 1 ? `<li class="col clearPos"><a href="javascript:void(0)"><div class="desc"><span>${more_text}</span><span>${tab_name}</span></div><i class="iconfont icon-more"></i></a></li>` : ''}`
                        : `<li class="col">
                                <a href="javascript:void(0)">
                                    <div class="desc nol"><span class="title">${i.product_name}</span>${i.product_price !== i.product_org_price ? `<span class="price">${i.product_price}元</span><del><span>${i.product_org_price}元</span></del>` : `<span class="price">${i.product_price}元</span>`}
                                    </div><img src="${i.img_url}">
                                </a>
                            </li>
                            <li class="col">
                                <a href="javascript:void(0)">
                                <div class="desc"><span>${more_text}</span><span>${tab_name}</span></div><i class="iconfont icon-more"></i></a></li>`
                    ).join("")
                    temp += '</div>'

                    return temp
                }).join("") + '</div>'}
                                
                            </div>
                        </div>
                `}).join("")

}

export default (() => {

    let homeMainPage = document.createElement("div")

    homeMainPage.classList.add("home-main-page");

    (async () => {

        const res = await axios.get("http://localhost:9000/api/homeinfopage");

        const { data: { home_info_list } } = res

        homeMainPage.innerHTML = render(
            {
                home_info_list: home_info_list.slice(0, 2)
            },
            {
                home_info_list: renderHomePageInfo
            },
            `
                <div class="home-main-page-wrapper auto">
                    <div class="home-banner"><img src="//cdn.cnbj1.fds.api.mi-img.com/mi-mall/f334fbd05d5681bb838fefd1c815d88c.jpg?thumb=1&w=1226&h=120&f=webp&q=90"></div>
                {{home_info_list}}
            `
        )

        const activeTabList = {}

        const activeTabListItems = {}

        // 处理TabList
        const handleTabList = (tabList, tabListItems) => {

            let tid = tabList ? tabList.children[0].getAttribute("tid") : null

            if (!tid) {
                tabList = [...homeMainPage.querySelectorAll(".tab-list")].filter(i => !i.classList.contains("on"))[0]
                tid = tabList.children[0].getAttribute("tid")
                tabListItems = [...homeMainPage.querySelectorAll(".tab-list-item")].filter(i => tid === i.getAttribute("tid"))
            }

            tabList.classList.add("on")

            tabList.addEventListener("mouseover", function (e) {

                const { target } = e
                if (target.nodeName === 'DIV') return

                const curtId = target.getAttribute("tid");

                activeTabList[curtId].forEach(i => {
                    if (i.classList.contains("active")) {
                        if (i !== target) {
                            i.classList.remove("active")
                            target.classList.add("active")
                            activeTabListItems[curtId].forEach(i => {
                                (i.classList.contains("active")
                                    ? i.classList.remove("active")
                                    : (i.getAttribute("tname") === target.innerText ? i.classList.add("active") : ''))
                            })
                        }
                    }
                })
            })
            activeTabList[tid] = [...tabList.children]
            activeTabListItems[tid] = tabListItems
        }

        handleTabList(homeMainPage.querySelector(".tab-list"), homeMainPage.querySelectorAll(".tab-list-item"))

        const homeMainPageWrapper = homeMainPage.querySelector(".home-main-page-wrapper")

        const wh = window.innerHeight || window.clientHeight
        let currentIndex = 2
        const fh = footer.clientHeight
        window.addEventListener("scroll", debounce(function (e) {
            //文档内容实际高度（包括超出视窗的溢出部分）
            let scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
            //滚动条滚动距离
            let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

            scrollTop >= homeMainPageWrapper.offsetTop
                ? ToolBar.lastElementChild.style.display = 'flex'
                : ToolBar.lastElementChild.style.display = 'none'
            // console.log(ToolBar);
            if (scrollTop + wh >= scrollHeight - fh - 100) {

                if (currentIndex === home_info_list.length) return

                const newPageInfo = document.createElement("div")
                newPageInfo.classList.add("home-page-info")
                newPageInfo.innerHTML += renderHomePageInfo(home_info_list.slice(currentIndex, currentIndex + 1))
                homeMainPageWrapper.appendChild(newPageInfo)
                currentIndex++
                handleTabList()
                console.log("===加载更多内容……===");
            }
        }, 50))
    })()

    return homeMainPage

})()